import { defineEventHandler, getQuery } from 'h3'
import redis from '../../util/redis'
import { recordLog } from '../../util/log'

// GET /api/live/birthday.get?key=...
export default defineEventHandler(async (event) => {
  try {
    const q = getQuery(event) as any
    const key = q?.key ?? ''

    if (!key || typeof key !== 'string') {
      event.node.res.statusCode = 400
      return { status: 400, message: 'missing key' }
    }

    try {
      const value = await (redis as any).get(key)
      await recordLog(event as any, { message: `birthday: get key=${key} result=${value ? 'found' : 'notfound'}`, userId: 0 })
      if (value === null) {
        event.node.res.statusCode = 404
        return { status: 404, message: 'not found' }
      }
      let parsed = null
      try { parsed = JSON.parse(value) } catch (e) { parsed = { raw: value } }
      return { status: 'ok', key, value: parsed }
    } catch (err: any) {
      event.node.res.statusCode = 500
      await recordLog(event as any, { message: `birthday: redis get failed ${String(err)}`, userId: 0 })
      return { status: 500, message: 'redis get failed', error: String(err) }
    }
  } catch (err: any) {
    event.node.res.statusCode = 500
    await recordLog(event as any, { message: `birthday: internal error ${String(err)}`, userId: 0 })
    return { status: 500, message: 'internal error', error: String(err) }
  }
})
